<?php

namespace app\api\controller;


use app\admin\model\game\Config;
use app\admin\model\game\Record;
use app\common\controller\Api;
use app\common\helpers\CommonHelper;
use app\common\helpers\ImageUtil;
use think\Db;
use think\Model;
use function fast\e;

/**
 * pk接口
 */
class Game extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 发起pk
     */
    public function pkIndexCreate()
    {
        $user = $this->auth->getUser();
        if($user['member_expire_time'] < date('Y-m-d H:i:s')){
            $this->error("你不是会员,无法发起pk");
        }
        $model = new Record();
        $model->inviter_id = $user['id'];
        $model->create_time = date('Y-m-d H:i:s');
        $model->save();
        $pkConfig = Config::get(1);
        $data =[
            'active_id'=>$model->id,
            'sponsor'=>[
                'sponsor_name'=>$pkConfig['sponsor_name'],
                'sponsor_logo'=>ImageUtil::handle($pkConfig['sponsor_logo']),
                'sponsor_rate'=>$pkConfig['sponsor_rate'],
            ],
            'user'=>[
                'name'=>$user['nickname'],
                'logo'=>ImageUtil::handle($user['avatar']),
                'rate'=>$pkConfig['order_user_rate'],
            ],
        ];
        $this->success('successful', $data);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 受邀请者点击加入
     */
    public function pkIntoyq()
    {
        $active_id= $this->request->param('active_id');
        $user = $this->auth->getUser();
        $pkInfo = Record::get($active_id);

        if($pkInfo['invitee_id'] == $user['id']){
            $this->error("你已经在该PK中了",null,'1022');
        }
        if($pkInfo['inviter_id'] == $user['id']){
            $this->error("你已经在该PK中了，请邀请好友",null,'1020');
        }
        if($pkInfo['invitee_id'] > 0)   $this->error("pk人已经满了");
        $result = Record::update(['invitee_id'=>$user['id']],['id'=>$active_id]);
        if($result){
            $this->success("进入成功");
        }else{
            $this->error("你已经进入pk中了",null,'1021');
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查看pk信息
     */
    public function pkInfo()
    {
        $user = $this->auth->getUser();
        $active_id= $this->request->param('active_id');
        $pkInfo = Record::get($active_id);
        $pkConfig = Config::get(1);
        $recipient_name = '';
        $recipient_logo = '';
        if($pkInfo && $pkInfo['invitee_id']){
            $invitee_info = \app\admin\model\User::get($pkInfo['invitee_id']);
            $recipient_name = $invitee_info['nickname'];
            $recipient_logo = $invitee_info['avatar'];
        }
        $inviter_info = \app\admin\model\User::get($pkInfo['inviter_id']);
        $data =[
            'active_id'=>$active_id,
            'game_result'=>$pkInfo['status'],
            'end_time'=>$pkInfo['end_time'],
            'status'=> ($pkInfo['invitee_id'] && $pkInfo['inviter_id']) ? 1 : 2,
            'sponsor'=>[
                'sponsor_name'=>$pkConfig['sponsor_name'],
                'sponsor_logo'=>ImageUtil::handle($pkConfig['sponsor_logo']),
                'sponsor_rate'=>$pkConfig['sponsor_rate'],
            ],
            'user'=>[
                'name'=>$inviter_info['nickname'],
                'logo'=>ImageUtil::handle($inviter_info['avatar']),
                'rate'=>$pkConfig['order_user_rate'],
            ],
            'recipient'=>[
                'name'=>$recipient_name,
                'logo'=>ImageUtil::handle($recipient_logo),
                'rate'=>$pkConfig['payment_user_rate'],
            ],
        ];
        $this->success("获取成功",$data);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * pk 开始
     */
    public function pkStart()
    {
        $user = $this->auth->getUser();
        $active_id= $this->request->param('active_id');
        $pkInfo = Record::get($active_id);
        if(!$pkInfo) $this->error("pk不存在");
        if($pkInfo['end_time']) $this->error("pk已结束");
        if($pkInfo['inviter_id'] && $pkInfo['invitee_id']){
            $pkConfig = Config::get(1);
            $num1_rate = $pkConfig['sponsor_rate'] > 0 ? $pkConfig['sponsor_rate']/100 : 0.01;
            $result =  CommonHelper::getRut($pkConfig['payment_user_rate'],$pkConfig['order_user_rate'],$num1_rate);
            Db::startTrans();
            try {
                   $data =['status'=>$result,'end_time'=>date('Y-m-d H:i:s')];
                //如果选中的是平台 获取平台红包
                if($result == 3){
                   $data['red_amount'] = $pkConfig['red_amount'];
                   \app\common\model\User::money($pkConfig['red_amount'],$pkInfo['inviter_id'],'游戏pk',2,$active_id);
                    \app\common\model\User::money($pkConfig['red_amount'],$pkInfo['invitee_id'],'游戏pk',2,$active_id);
                }
                $isUplod = Record::update($data,['id'=>$active_id]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
            }

            if($isUplod){
                $this->success("获取成功",$result);
            }
            $this->error("pk失败，请重试！");
        }else{
            $this->error("还差一个人");
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取pk记录
     */
    public function pkRecordList()
    {
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $type = $this->request->param('type');//0-发起 1-结果
        $user = $this->auth->getUser();
        $where['inviter_id'] = $user['id'];
        if($type == '1'){
            $where['status']= ['>',0];
        }else{
            $where['status']= ['null',''];
        }
        $model = (new Record())
            ->where($where)
            ->order('create_time desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        $userList = \app\admin\model\User::field('id,nickname,avatar')->select();
        $userList = array_column($userList,null,'id');
        if($list){
            foreach ($list as &$v){
                $v['invitee_info'] = isset($userList[$v['invitee_id']]) ? $userList[$v['invitee_id']] : [];
                $v['inviter_info'] = isset($userList[$v['inviter_id']]) ? $userList[$v['inviter_id']] : [];
                if($type == '0'){
                    $v['describe'] = intval($v['invitee_id']) <= 0 ? '你发起了一次pk,还没有人参与!' :  '你发起了一次pk,好友已加入,请开始pk' ;
                }
            }
        }
        $this->success('successful', array("total" =>$total , "list" => $list));
    }



    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取消息通知
     */
    public function pkNoticeList()
    {
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $user = $this->auth->getUser();
        $where['status']= ['>',0];
        $where['inviter_id'] = $user['id'];
        $model = (new Record())
            ->field('id,inviter_id,invitee_id,status,end_time,red_amount')
            ->where($where)
//            ->whereOr('invitee_id',$user['id'])
            ->order('end_time desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        $userList = \app\admin\model\User::field('id,nickname,avatar')->select();
        $userList = array_column($userList,null,'id');
        if($list){
            foreach ($list as &$v){
//                if ($v['inviter_id'] == $user['id']) {
                    $v['invitee_info'] = isset($userList[$v['invitee_id']]) ? $userList[$v['invitee_id']] : [];
                    $v['describe'] = '你与'.$userList[$v['invitee_id']]['nickname'].'pk,';
                    if($v['status'] == '1'){
                        $v['describe'] =$v['describe'].'你赢了,快点去点一杯吧。';
                    }
                    if($v['status'] == '2'){
                        $v['describe'] =$v['describe'].'你输了,再来一次。';
                    }
                    if($v['status'] == '3'){
                        $v['describe'] =$v['describe'].'平局,获得平台红包'.$v['red_amount'].'元。';
                    }
//                }else{
//                    $v['invitee_info'] = isset($userList[$v['inviter_id']]) ? $userList[$v['inviter_id']] : [];
//                    $v['describe'] = '你与'.$userList[$v['inviter_id']]['nickname'].'pk,';
//                    if($v['status'] == '1'){
//                        $v['describe'] =$v['describe'].'你输了,让朋友点一杯吧。';
//                    }
//                    if($v['status'] == '2'){
//                        $v['describe'] =$v['describe'].'你赢了,快点去点一杯吧。';
//                    }
//                    if($v['status'] == '3'){
//                        $v['describe'] =$v['describe'].'平局,获得平台红包'.$v['red_amount'].'元。';
//                    }
//                }
            }
        }
        $this->success('successful', array("total" =>$total , "list" => $list));
    }

}
